const express = require("express");
const router = express.Router();
const { User } = require("../models");
const { success, failure } = require("../utils/responses");
const { NotFound, BadRequest, Unauthorized } = require("http-errors");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const { Op } = require("sequelize");
// 引入【图像验证码】中间件
const validateCaptcha = require("../middlewares/validate-captcha");
const { delKey } = require("../utils/redis");
const { mailProducer } = require("../utils/rabbit-mq");

/**
 * 用户注册
 * POST /auth/sign_up
 */
router.post("/sign_up", validateCaptcha, async function (req, res) {
  try {
    const body = {
      email: req.body.email,
      username: req.body.username,
      nickname: req.body.nickname,
      password: req.body.password,
      sex: 2, // 默认为未选择
      role: 0, // 默认为普通用户
    };

    const user = await User.create(body);
    // 密码不返回
    delete user.dataValues.password;

    // 请求成功，删除 redis 验证码，防止重复使用
    await delKey(req.body.captchaKey);

    // 将邮件发送请求放入队列
    const msg = {
      to: user.email,
      subject: "「信念不结冰」的注册成功通知",
      html: `
        您好，<span style="color: red">${user.nickname}</span>。<br><br>
        恭喜，您已成功注册会员！<br><br>
        请访问<a href="http://swq2024.github.io/">「信念不结冰」</a>官网，了解更多。<br><br>
        ━━━━━━━━━━━━━━━━<br>
        信念不结冰
      `,
    };
    await mailProducer(msg);

    success(res, "创建用户成功。", { user }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 用户登录
 * POST /auth/sign_in
 */
router.post("/sign_in", async (req, res) => {
  try {
    // 生成32位随机字符串
    // console.log(crypto.randomBytes(32).toString("hex"));

    // login 既可以填写邮箱，也可以填写用户名
    const { login, password } = req.body;

    if (!login) {
      throw new BadRequest("邮箱/用户名必须填写。");
    }

    if (!password) {
      throw new BadRequest("密码必须填写。");
    }

    const condition = {
      where: {
        [Op.or]: [{ email: login }, { username: login }],
      },
    };

    // 通过email或username，查询用户是否存在
    const user = await User.findOne(condition);

    if (!user) {
      throw new NotFound("用户不存在，请先注册");
    }

    // 验证密码
    const isPasswordValid = bcrypt.compareSync(password, user.password);
    if (!isPasswordValid) {
      throw new Unauthorized("密码错误，请重新输入");
    }

    // 生成token
    const token = jwt.sign(
      // payload: 存放在token中的信息，可以自定义
      {
        userId: user.id, // 管理员id
        // username: user.username,
      },
      // 密钥
      process.env.JWT_SECRET,
      // 有效期
      { expiresIn: "30d" }
    );

    success(res, "登录成功", { token });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
